local evl_Clock = CreateFrame("Button", nil, UIParent)

local text

local AddonsMemoryCompare = function(a, b)
	return a.memory > b.memory
end

local FormatMemoryNumber = function(number)
	if number > 1000 then
		return string.format("%.2f mb", number / 1000)
	else
		return string.format("%.1f kb", number)
	end
end

local ColorizeLatency = function(number)
	if number <= 100 then
		return {r = 0, g = 1, b = 0}
	elseif number <= 200 then
		return {r = 1, g = 1, b = 0}
	else
		return {r = 1, g = 0, b = 0}
	end
end

local lastUpdate = 0
function evl_Clock:onUpdate(elapsed)
	lastUpdate = lastUpdate + elapsed
	
	if lastUpdate > 1 then
		lastUpdate = 0
		text:SetText(date("%H:%M"))
	end
end

local memoryFormat = "%.2f %s"
local latency, latencyColor, addons, totalMemory
local memory, addon, i
function evl_Clock:onEnter()
	latency = select(3, GetNetStats())
	latencyColor = ColorizeLatency(latency)
	
	GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
	GameTooltip:AddLine(string.format("Latency: %d ms", latency), latencyColor.r, latencyColor.g, latencyColor.b)
	GameTooltip:AddLine(string.format("Framerate: %.1f", GetFramerate()), 1, 1, 1)
	GameTooltip:AddLine("\n")
	
	addons = {}
	totalMemory = 0
	
	UpdateAddOnMemoryUsage()

	for i=1, GetNumAddOns(), 1 do
		memory = GetAddOnMemoryUsage(i)
		addon = {name = GetAddOnInfo(i), memory = memory}
		table.insert(addons, addon)
		
		totalMemory = totalMemory + memory
	end
	
	table.sort(addons, AddonsMemoryCompare)
	
	i = 0
	for _, addon in pairs(addons) do
		GameTooltip:AddDoubleLine(addon.name, FormatMemoryNumber(addon.memory), 1, 1, 1, 1, 1, 1)
		
		i = i + 1
		
		if i >= 10 then
			break
		end
	end
	
	GameTooltip:AddLine("\n")
	GameTooltip:AddDoubleLine("Total", FormatMemoryNumber(totalMemory), 1, 1, 0, 1, 1, 0)
	
	GameTooltip:Show()
end

function evl_Clock:new()
	self:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", -3, -3)
	self:SetWidth(50)
	self:SetHeight(16)
	
	self:SetScript("OnUpdate", self.onUpdate)
	self:SetScript("OnEnter", self.onEnter)
	self:SetScript("OnLeave", function() GameTooltip:Hide() end)
	
	text = self:CreateFontString(nil, "ARTWORK")
	text:SetFontObject(GameFontHighlightSmall)
	text:SetPoint("TOPRIGHT", self)
end

evl_Clock:new()